package com.codebo.homiematch.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codebo.homiematch.mapper.ChatMapper;
import com.codebo.homiematch.mapper.UserMapper;
import com.codebo.homiematch.model.dto.ChatDTO;
import com.codebo.homiematch.model.entity.Chat;
import com.codebo.homiematch.model.entity.User;
import com.codebo.homiematch.model.vo.ChatVO;
import com.codebo.homiematch.service.ChatService;
import com.codebo.homiematch.service.UserService;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 25912
 * @description 针对表【chat(聊天消息)】的数据库操作Service实现
 * @createDate 2025-07-24 20:58:12
 */
@Service
public class ChatServiceImpl extends ServiceImpl<ChatMapper, Chat>
        implements ChatService
{

    @Resource
    private ChatMapper chatMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public ChatVO saveChat(ChatDTO chatDTO)
    {
        Chat chat = new Chat();
        BeanUtil.copyProperties(chatDTO, chat);
        save(chat);
        chat = getById(chat.getId());
        User user = userService.getById(chat.getFromId());
        ChatVO chatVO = new ChatVO();
        BeanUtil.copyProperties(chat, chatVO);
        chatVO.setAvatar(user.getAvatar());
        chatVO.setNickname(user.getNickname());
        return chatVO;

        //发送消息
    }

    @Override
    public List<ChatVO> chatList()
    {
        List<Chat> chatList = chatMapper.selectList(new QueryWrapper<>());
        List<ChatVO> chatVOList = chatList.stream().map(this::getChatVO).collect(Collectors.toList());
        return chatVOList;
    }

    @Override
    public ChatVO getChatVO(Chat chat)
    {
        ChatVO chatVO = new ChatVO();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", chat.getFromId());
        User user = userMapper.selectOne(queryWrapper);
        chatVO.setFromId(chat.getFromId());
        chatVO.setAvatar(user.getAvatar());
        chatVO.setNickname(user.getNickname());
        chatVO.setText(chat.getText());
        chatVO.setCreateTime(chat.getCreateTime());
        return chatVO;
    }


}




